//
//  CModelAction.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/8/1.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "CModelAction.h"
#define IS_OS_9_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
@implementation CModelAction

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;


- (id) initWithTableName:(NSString *) tablename{
    self = [super init];
    if (self) {
        self.tableName = tablename;
    }
    return self;
}

- (NSMutableArray *) fetchOneWithWhere:(NSString *)where WithOrder:(NSString *)order{
    NSMutableArray *data = [self fetchDataWithWhere:where WithOrder:order WithLimit:1];
    if (data.count) {
        return [data objectAtIndex:0];
    }else
        return nil;
}

- (NSMutableArray*) fetchDataWithWhere:(NSString *)where WithOrder:(NSString *) order WithLimit:(NSInteger)limit{
    return [self fetchDataWithWhere:where WithOrder:order WithLimit:limit FromOffset:0];
}

- (NSMutableArray*) fetchDataWithWhere:(NSString *)where WithOrder:(NSString *) order WithLimit:(NSInteger)limit FromOffset:(NSInteger) offset{
    //创建取回数据请求
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    //设置要检索哪种类型的实体对象
    NSEntityDescription *entity = [NSEntityDescription entityForName:self.tableName
                                              inManagedObjectContext:self.managedObjectContext];
    //设置请求实体
    [request setEntity:entity];
    //指定对结果的排序方式
    NSArray *or_array = [order componentsSeparatedByString:@", "];
    for (NSString *o in or_array) {
        NSArray *o_array = [o componentsSeparatedByString:@" "];
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[o_array objectAtIndex:0]
                                                                       ascending:[[o_array objectAtIndex:1] caseInsensitiveCompare:@"asc"] == NSOrderedSame];
        NSArray *sortDescriptions = [[NSArray alloc]initWithObjects:sortDescriptor, nil];
        [request setSortDescriptors:sortDescriptions];
    }
    
    [request setFetchLimit:limit];
    [request setFetchOffset:offset];
    if (where && ![where isEqualToString:@""]) {
        NSPredicate *predict = [NSPredicate predicateWithFormat:where];
        [request setPredicate:predict];
    }
    
    NSError *error = nil;
    //执行获取数据请求，返回数组
    NSMutableArray *mutableFetchResult = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    
#ifdef  __IPHONE_OS_VERSION_MIN_REQUIRED
#if __IPHONE_OS_VERSION_MAX_ALLOWED > 80400
    if (IS_OS_9_OR_LATER) {
        [self.managedObjectContext refreshAllObjects];
    }
#endif
#endif
    if (mutableFetchResult == nil) {
        echo(([NSString stringWithFormat:@"Error: %@,%@",error,[error userInfo]]));
    }
    return mutableFetchResult;
}

- (void) InsertData:(id *) table{
    *table = [NSEntityDescription insertNewObjectForEntityForName:self.tableName
                                           inManagedObjectContext:self.managedObjectContext];
}

- (BOOL) DeleteData:(id *) table{
    [self.managedObjectContext deleteObject:*table];
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            echo(([NSString stringWithFormat:@"Unresolved error %@, %@", error, [error userInfo]]));
            abort();
            return false;
        }
    }
    return true;
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        //        if ([managedObjectContext hasChanges]) {
        //            echo(@"yes");
        //        }
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            echo(([NSString stringWithFormat:@"Unresolved error %@, %@", error, [error userInfo]]));
            abort();
        }
    }
    
#ifdef  __IPHONE_OS_VERSION_MAX_ALLOWED
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= 80400
    [self.managedObjectContext reset];
#endif
#endif
}

#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Model.sqlite"];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.
         
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         
         */
        echo(([NSString stringWithFormat:@"Unresolved error %@, %@", error, [error userInfo]]));
        abort();
    }
    
    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


@end
